package me.zingon.doc.controller;


import me.zingon.doc.exception.ServiceException;
import me.zingon.doc.service.UserService;
import me.zingon.doc.model.User;
import java.util.List;
import java.util.Map;

import me.zingon.doc.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
* Created by ZTCGenerator<zingon@aliyun.com> on 2018-5-31.
*/
@RestController
@RequestMapping("/user")
public class UserController{

    @Autowired
    UserService userService;
    @Autowired
    EmailUtil emailUtil;

    @PostMapping("/login")
    public Object login(@RequestBody Map<String,String> map) throws ServiceException {
        String loginName = map.get("loginName");
        String password = map.get("password");
        return userService.login(loginName,password);
    }

    @PostMapping("/register")
    public Object register(@RequestBody User user) throws ServiceException {
        if(userService.checkNickname(user.getNickname()) != 0){
            throw new ServiceException("user.exists.nickname");
        }
        if(userService.checkEmail(user.getLoginName()) != 0){
            throw new ServiceException("user.exists.email");
        }
        return userService.register(user);
    }


    @PostMapping("/check")
    public Object check(@RequestBody Map<String,String> check) throws ServiceException {
        if(check.get("nickname")!=null && userService.checkNickname(check.get("nickname")) != 0){
            throw new ServiceException("user.exists.nickname");
        }
        if(check.get("email")!=null && userService.checkEmail(check.get("email")) != 0){
            throw new ServiceException("user.exists.email");
        }
        return 1;
    }

    @GetMapping("/active/{token}")
    public Object active(@PathVariable("token")String token) throws ServiceException {
        return userService.activeUser(token);
    }

}
